"""
闲鱼机器人主程序入口
默认启动GUI。如需仅运行命令行模式，可设置环境变量 RUN_MODE=cli
"""

import os
import sys
import asyncio
from loguru import logger
from dotenv import load_dotenv

from core.xianyu_client import XianyuClient

# 版本信息
VERSION = "1.0.0"
DATE = "2025112702"
APP_TITLE = f"闲鱼机器人 v{VERSION} {DATE}"


def run_cli():
    load_dotenv()
    cookies_str = os.getenv('COOKIE', '')
    if not cookies_str:
        logger.error("未找到COOKIE配置，请检查.env文件")
        sys.exit(1)
    logger.debug("成功加载Cookie配置")
    client = XianyuClient(cookies_str)
    try:
        asyncio.run(client.main())
    except KeyboardInterrupt:
        logger.debug("程序被用户中断")
    except Exception as e:
        logger.error(f"程序异常退出: {e}")


def run_gui():
    import customtkinter as ctk
    from ui import MainWindow
    ctk.set_appearance_mode("System")
    ctk.set_default_color_theme("blue")
    win = MainWindow()
    win.protocol("WM_DELETE_WINDOW", win.stop_auto_refresh_and_close)
    win.mainloop()


def main():
    mode = (os.getenv('RUN_MODE', 'gui') or 'gui').strip().lower()
    if mode == 'cli':
        run_cli()
    else:
        run_gui()


if __name__ == '__main__':
    main()

